import React, { Component } from 'react'
import { Spin } from 'antd'
import './index.css'

/**
 * @author liu_jshan
 * @version 1.1
 * @date 2024-02-19
 * @props {
 *  style：css样式，对象
 *  placeholder：说明文本，string,
 *  value: 初始值，string
 *  disabled: 是否禁用，boolean
 *  readOnly: 是否只读，boolean
 *  resize: 是否可调整大小，boolean
 *  rows: 初始行数，大于0的整数，默认为4
 *  onChange: 值变化的回调方法，function onChange(value)
 *  prefixName: 前缀，对象 {
 *    content: 前缀内容, string or 图标组件
 *    style: 前缀样式
 *  }
 *  rules：校验，array
 *    rules：[
 *      {
 *        validate: 校验的方法，需要返回布尔类型，function 参数为value
 *        failMessage: 校验不通过的提示信息，string
 *        successMessage: 校验通过的提示信息，string 非必须
 *      }
 *    ]
 *  suffixName：自定义后缀，string or 组件
 * }
 */
class TextAreaWidget extends Component {

    constructor(props) {
        super(props)
        this.state = {
            value: '', //当前的值
            lastValue: '', //原来的值
            validateMessage: '',//校验信息字符串
            validateMessageArr: [],//校验信息数组
            validateSuccess: true, //校验是否通过
            prefixDisplay: false, //前缀显隐
            suffixDisplay: true, //后缀显隐
            loading: false
        }
    }

    async componentDidMount() {
        let prefixDisplay = this.props.prefixName ? true : false //前缀显隐
        let value = this.props.value ? this.props.value : ''
        let suffixDisplay = this.props.readOnly !== true && this.props.disabled !== true && this.props.suffixName ? true : false

        await new Promise((resolve) => {
            this.setState({
                prefixDisplay,
                suffixDisplay,
                value,
                loading: false
            }, resolve)
        })
    }

    /**
   * 组件值变化时调用
   * @param {*} value 变化后的值
   * @param {*} callPropsChange 是否调用props的onChange回调函数，默认true
   */
    onChange = async (value, callPropsChange = true) => {
        //先赋值再校验
        let lastValue = this.state.value
        await new Promise(resolve => {
            this.setState({
                lastValue,
                value
            }, resolve)
        })

        await this.validateRules()

        if (callPropsChange && this.props.onChange && typeof this.props.onChange === 'function') {
            await this.props.onChange(value)
        }
    }

    validateRules = async () => {
        const value = this.state.value
        let validateMessageArr = []
        let validateMessage = ''
        let validateSuccess = true
        const { rules } = this.props
        if (rules && Array.isArray(rules) && rules.length > 0) {
            for (let i = 0; i < rules.length; i++) {
                const { validate, failMessage, successMessage } = rules[i]
                if (validate && typeof validate === 'function') {
                    let res = await validate(value)
                    if (res === false) {
                        if (validateSuccess === true && validateMessageArr.length > 0) { //之前校验的都是正确的
                            validateMessageArr = []
                        }
                        validateMessageArr.push(failMessage ? failMessage : '请配置校验提示信息！')
                        validateSuccess = false
                    } else if (res === true && validateSuccess === true && successMessage) {
                        validateMessageArr.push(successMessage)
                    }
                }
            }
            validateMessage = validateMessageArr.join('; ')
        }

        await new Promise(resolve => {
            this.setState({
                validateMessage,
                validateMessageArr,
                validateSuccess
            }, resolve)
        })

        return validateSuccess
    }

    render() {
        if (this.state.loading === true) return <Spin />
        return (
            <div className='TextAreaWidget-main' style={this.props.style}>
                <div
                    className='TextAreaWidget-textDiv'
                    style={this.state.validateSuccess === false ? { border: '1px solid var(--border-color-seven)' } : null}
                >
                    {
                        this.state.prefixDisplay === false ? '' :
                            <div className='TextAreaWidget-prefix' style={this.props.prefixName.style}>
                                {this.props.prefixName.content}
                            </div>
                    }
                    <textarea
                        className={!this.props.readOnly && this.props.disabled === true ? 'TextAreaWidget-textarea widget-disabled' : 'TextAreaWidget-textarea'}
                        style={this.props.resize === false || this.props.disabled === true || this.props.readOnly === true ? { resize: 'none' } : null}
                        placeholder={this.props.placeholder}
                        rows={this.props.rows ? this.props.rows : 4}
                        disabled={this.props.disabled}
                        readOnly={this.props.readOnly}
                        value={this.state.value}
                        onChange={event => this.onChange(event.target.value)}
                        ref={ref => { this.textareaRef = ref }}
                    ></textarea>
                    {
                        this.state.suffixDisplay === false ? '' :
                            <div className='TextAreaWidget-suffix'>
                                {this.props.suffixName ? this.props.suffixName : ''}
                            </div>
                    }
                </div>
                <div className='TextAreaWidget-messageDiv'
                    style={{ color: this.state.validateSuccess === true ? 'var(--ordinary-font-color)' : 'var(--danger-font-color)' }}
                >
                    {this.state.validateMessage}
                </div>
            </div>
        )
    }
}

export default TextAreaWidget
